<template>
    <div>
        <div class="toolbar">
            <div>
                <img style="margin: 17px 0 0 27px;" src="../assets/img/LOGO.png" alt="">
            </div>
            <div class="toolbaritem" style="margin-left: -15%;">
                <div class="group">
                    <el-tooltip class="item" effect="dark" content="撤销" placement="bottom">
                        <div class="button borderRight" size="mini" @click="undo">
                            <img src="../assets/img/icon_撤销_hover.png" alt="">
                        </div>
                    </el-tooltip>

                    <el-tooltip class="item" effect="dark" content="恢复" placement="bottom">
                        <div class="button borderLeft" size="mini" @click="redo">
                            <img src="../assets/img/icon_恢复_hover.png" alt="">
                        </div>
                    </el-tooltip>
                </div>

                <el-tooltip class="item" effect="dark" content="插入图片" placement="bottom">
                    <div class="group other">

                        <label for="input" class="insert button">
                            <img src="../assets/img/icon_插入图片_hover.png" alt="">
                        </label>
                        <input type="file" @change="handleFileChange" id="input" hidden />
                    </div>
                </el-tooltip>

                <div class="group">
                    <el-tooltip class="item" effect="dark" content="组合" placement="bottom">
                        <div class="button borderRight" size="mini" @click="compose" :class="!areaData.components.length?'disabled':''">
                            <img src="../assets/img/icon_组合_hover.png" alt="">
                        </div>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="拆分" placement="bottom">
                        <div class="button borderLeft" size="mini" @click="decompose" :class="!curComponent || curComponent.isLock || curComponent.component != 'Group'?'disabled':''">
                            <img src="../assets/img/icon_拆分_hover.png" alt="">
                        </div>
                    </el-tooltip>
                </div>

                <div class="group">
                    <el-tooltip class="item" effect="dark" content="组件锁定" placement="bottom">
                        <div class="button borderRight" size="mini" @click="lock" :class="!curComponent || curComponent.isLock?'disabled':''">
                            <img src="../assets/img/icon_锁定_hover.png" alt="">
                        </div>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="组件解锁" placement="bottom">
                        <div class="button borderLeft" size="mini" @click="unlock" :class="!curComponent || !curComponent.isLock?'disabled':''">
                            <img src="../assets/img/icon_解锁_hover.png" alt="">
                        </div>
                    </el-tooltip>
                </div>
                <div class="group" style="width: 35px;">
                    <el-tooltip class="item" effect="dark" content="云渲染" placement="bottom">
                        <div class="button borderRight" size="mini" @click="showInfo">
                            <img src="../assets/img/icon_连接.png" alt="">
                        </div>
                    </el-tooltip>
                </div>

                <div class="group">
                    <el-tooltip class="item" effect="dark" content="三维锁定" placement="bottom">
                        <div class="button borderRight" size="mini" @click="cloudLock" :class="!$store.state.changeCloudWeb?'disabled':''">
                            <img src="../assets/img/icon_锁定_hover.png" alt="">
                        </div>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="三维解锁" placement="bottom">
                        <div class="button borderLeft" size="mini" @click="cloudNotLock" :class="$store.state.changeCloudWeb?'disabled':''">
                            <img src="../assets/img/icon_解锁_hover.png" alt="">
                        </div>
                    </el-tooltip>
                </div>
            </div>

            <div class="toolbaritem" style="margin-right: -15%;">

                <div class="canvas-config">
                    <span>画布大小</span>
                    <input v-model="canvasStyleData.width">
                    <span>*</span>
                    <input v-model="canvasStyleData.height">
                </div>
                <div class="canvas-config">
                    <span>画布比例</span>
                    <input v-model="scale" @input="handleScaleChange"> %
                </div>
            </div>
            <div class="toolbaritem">
                <div class="button btmRight" style="width:80px;" size="mini" @click="clearCanvas">清空画布</div>
                <div class="button btmRight" size="mini" @click="preview" style="margin-left: 10px;">预览</div>
                <div class="button btmRight" size="mini" @click="save">保存</div>
            </div>

        </div>

        <!-- 预览 -->
        <Preview v-model="isShowPreview" @change="handlePreviewChange" />
    </div>
</template>

<script>
import generateID from '@/utils/generateID'
import toast from '@/utils/toast'
import { mapState } from 'vuex'
import Preview from '@/components/Editor/Preview'
import { commonStyle, commonAttr } from '@/custom-component/component-list'
import eventBus from '@/utils/eventBus'
import { deepCopy } from '@/utils/utils'

export default {
    components: { Preview },
    data() {
        return {
            isShowPreview: false,
            needToChange: ['top', 'left', 'width', 'height', 'fontSize', 'borderWidth'],
            scale: '100%',
            timer: null,
            aircityPlayer: null,
            aircityApi: null,
            showTableInfo: false,
            changeCloudWeb: false,
        }
    },
    computed: mapState(['componentData', 'canvasStyleData', 'areaData', 'curComponent', 'dynamicTags']),
    created() {
        eventBus.$on('preview', this.preview)
        eventBus.$on('save', this.save)
        eventBus.$on('clearCanvas', this.clearCanvas)

        this.scale = this.canvasStyleData.scale
    },
    methods: {
        cloudLock() {
            this.$store.commit('setchangeCloudWeb', false)
        },
        cloudNotLock() {
            this.$store.commit('setchangeCloudWeb', true)
        },
        showInfo() {
            this.$store.commit('setshowTableInfo', true)
        },
        format(value) {
            const scale = this.scale
            return (value * parseInt(scale)) / 100
        },

        getOriginStyle(value) {
            const scale = this.canvasStyleData.scale
            const result = value / (parseInt(scale) / 100)
            return result
        },

        handleScaleChange() {
            clearTimeout(this.timer)
            // 画布比例设一个最小值，不能为 0
            // eslint-disable-next-line no-bitwise
            this.scale = ~~this.scale || 1
            this.timer = setTimeout(() => {
                const componentData = deepCopy(this.componentData)
                componentData.forEach(component => {
                    Object.keys(component.style).forEach(key => {
                        if (this.needToChange.includes(key)) {
                            // 根据原来的比例获取样式原来的尺寸
                            // 再用原来的尺寸 * 现在的比例得出新的尺寸
                            component.style[key] = this.format(this.getOriginStyle(component.style[key]))
                        }
                    })
                })

                this.$store.commit('setComponentData', componentData)
                this.$store.commit('setCanvasStyle', {
                    ...this.canvasStyleData,
                    scale: this.scale,
                })
            }, 500)
        },

        lock() {
            if (!this.curComponent || this.curComponent.isLock) {
                return
            } else {
                this.$store.commit('lock')
            }
        },

        unlock() {
            if (!this.curComponent || !this.curComponent.isLock) {
                return
            } else {
                this.$store.commit('unlock')
            }
        },

        compose() {
            if (this.areaData.components.length) {
                this.$store.commit('compose')
                this.$store.commit('recordSnapshot')
            }
        },

        decompose() {
            if (!this.curComponent || this.curComponent.isLock || this.curComponent.component != 'Group') {
                return
            } else {
                this.$store.commit('decompose')
                this.$store.commit('recordSnapshot')
            }
        },

        undo() {
            this.$store.commit('undo')
        },

        redo() {
            this.$store.commit('redo')
        },

        handleFileChange(e) {
            const file = e.target.files[0]
            if (!file.type.includes('image')) {
                toast('只能插入图片')
                return
            }

            const reader = new FileReader()
            reader.onload = res => {
                const fileResult = res.target.result
                const img = new Image()
                img.onload = () => {
                    this.$store.commit('addComponent', {
                        component: {
                            ...commonAttr,
                            id: generateID(),
                            component: 'Picture',
                            label: '图片',
                            icon: '',
                            propValue: fileResult,
                            style: {
                                ...commonStyle,
                                left: 0,
                                top: 0,
                                width: img.width,
                                height: img.height,
                            },
                        },
                    })

                    this.$store.commit('recordSnapshot')
                }

                img.src = fileResult
            }

            reader.readAsDataURL(file)
        },

        preview() {
            this.isShowPreview = true
            this.$store.commit('setEditMode', 'preview')
            if (this.$store.state.airCityPlayer) {
                // this.onLoad()
                this.$store.state.airCityPlayer.destroy()
                __g.destroy()
                this.$store.commit('setairCityPlayer', null)
                this.$store.commit('setaircityApi', null)
                let options = {
                    domId: 'player',
                    token: HostConfig.Token,
                    showMarker: true,
                    showStartupInfo: true,
                }
                let instanceId = this.$store.state.CurrentInstanceId
                console.log(instanceId)
                setTimeout(() => {
                    this.aircityPlayer = new AirCityPlayer(instanceId, options)
                    this.$store.commit('setairCityPlayer', this.aircityPlayer)
                    this.aircityApi = new AirCityAPI(instanceId, {
                        onReady: () => {},
                        onApiVersion: (vNo, vType) => {},
                        onEvent: e => {
                            console.log(e)
                            this.$store.commit('saveOnEvent', e)
                        },
                        onLog: e => {},
                        useColorLog: false, //仅用于SDK测试页面，二次开发请设置为false
                    })
                    this.$store.commit('setaircityApi', this.aircityApi)
                    console.log(instanceId)
                }, 1000)
            }
        },

        save() {
            localStorage.setItem('canvasData', JSON.stringify(this.componentData))
            localStorage.setItem('canvasStyle', JSON.stringify(this.canvasStyleData))
            localStorage.setItem('pageInfo', JSON.stringify(this.dynamicTags))
            this.$message.success('保存成功')
        },

        clearCanvas() {
            this.$store.commit('setComponentData', [])
            this.$store.commit('recordSnapshot')
        },

        handlePreviewChange() {
            this.$store.commit('setEditMode', 'edit')
        },
    },
}
</script>

<style lang="scss" scoped>
.toolbar {
    height: 55px;
    line-height: 55px;
    background: #1a1f32;
    border-bottom: 1px solid #000;
    display: flex;
    justify-content: space-between;
    padding-right: 15px;
    .toolbaritem {
        display: flex;
        align-items: center;
    }
    .canvas-config {
        display: inline-block;
        margin-left: 10px;
        font-size: 14px;
        color: #ffffff99;

        input {
            width: 50px;
            margin-left: 10px;
            outline: none;
            padding: 0 5px;
            border: 1px solid #39435d;
            color: #ffffff99;
            background: #161a2c;
        }

        span {
            margin-left: 10px;
        }
    }

    .insert {
        &:hover {
            cursor: pointer;
            background: #5bc4d633;
        }
    }
}
.group {
    width: 70px;
    height: 22px;
    background: #2d3142;
    border-radius: 4px;
    display: flex;
    margin: 0 4.5px;
    line-height: 22px;
}
.other {
    width: 35px;
}
.button {
    width: 35px;
    border-radius: 4px;
    text-align: center;
    &:hover {
        cursor: pointer;
        background: #5bc4d633;
    }
    &:active {
        border: 1px solid #11c4e46b;
    }
}
.button + .button {
    margin-left: 0px !important;
}
img {
    margin-top: 2px;
}
.borderRight {
    border-radius: 4px 0 0 4px;
    border-right: 1px solid #d7dce313;
}
.borderLeft {
    border-radius: 0 4px 4px 0;
    border-left: 1px solid #d7dce321;
}
.btmRight {
    width: 54px;
    height: 28px;
    color: #ffffff99;
    line-height: 28px;
    line-height: 28px;
    font-size: 12px;
    background: #252d42;
    margin: 0 4.5px;
    &:hover {
        cursor: pointer;
        background: #5bc4d633;
    }
}
.disabled {
    cursor: not-allowed;
    opacity: 0.5;
    background: #000;
    &:hover {
        cursor: not-allowed;
        background: #000;
    }
}
.input-with-select {
    width: 70%;
    margin-left: 5%;
}
</style>